<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :destroy-on-close="true"
    @ok="handleSubmit"
    width="800px"
    ok-text="保存"
  >
    <BasicForm @register="registerForm">
      <template #colorPickerSlot="{ model, field }">
        <ColorPicker v-model="model[field]" />
      </template>
      <template #deleteSlot="{ field }">
        <a-button type="link" danger @click="handleDelete(field)">删除</a-button>
      </template>
    </BasicForm>
    <a-button v-if="showAddButton" class="mt-2" @click="handleAdd">新增数据源</a-button>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form';
  import ColorPicker from '/@/components/ColorPicker/main.vue';
  import { modalFormStyleSetting, modalStyleSetting } from '/@/settings/thingsBoardDesign';
  import {
    dashboardChartschemas,
    widgetsChartSchemas,
    getAddSchemas,
    setDeviceOptionsParams,
  } from './chartModal.data';
  import { ref } from 'vue';
  import { getDeviceInfo } from '/@/api/thingsborad/entity/entity';

  const emits = defineEmits(['success']);
  const seriesLength = ref<number>(0);
  const entityName = ref<string>();
  const showAddButton = ref<boolean>(false);

  const [
    registerForm,
    { validate, setFieldsValue, appendSchemaByField, removeSchemaByField, resetSchema },
  ] = useForm({
    layout: 'vertical',
    showActionButtonGroup: false,
    ...modalFormStyleSetting,
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(
    async ({ whereFrom, formData }: { whereFrom: string; formData: Recordable }) => {
      setModalProps({
        ...modalStyleSetting,
      });
      if (whereFrom == 'widgetsLibrary') {
        resetSchema(widgetsChartSchemas);
        setFieldsValue({
          ...formData,
        });
      } else if (whereFrom == 'dashboard') {
        showAddButton.value = true;
        resetSchema([...widgetsChartSchemas, ...dashboardChartschemas]);
        if (!formData) return;
        await setFieldsValue({
          ...formData,
        });
        // 拿到设备名称去请求options数据
        if (formData.deviceId) {
          entityName.value = (await getDeviceInfo(JSON.parse(formData.deviceId).id)).name;
          setDeviceOptionsParams(entityName.value);
          // 设置series项数据
          seriesLength.value = formData.series.length;
          for (let i = 0; i < seriesLength.value; i++) {
            await appendSchemaByField(getAddSchemas(i), '');
          }
          setFieldsValue({
            series: formData.series,
          });
        }
      }
    },
  );

  // 添加series项
  function handleAdd() {
    appendSchemaByField(getAddSchemas(seriesLength.value), '');
    seriesLength.value += 1;
  }
  // 删除series项
  function handleDelete(field: string) {
    removeSchemaByField([
      `series.${Number(field)}.key`,
      `series.${Number(field)}.name`,
      `series.${Number(field)}.color`,
      `${Number(field)}`,
    ]);
  }

  async function handleSubmit() {
    const formData = await validate();
    emits('success', formData);
    closeModal();
  }
</script>
